const constant = require('constant.js')
const {
  version,
  server_env,
  debug
} = {
  ...constant
}
let showDialog = 0
/**
 * 请求头
 */
var header = {
  'content-type': 'application/json;charset=UTF-8',
}

/**
 * 供外部post请求调用  
 */
function post(loadingStr, url, params, onSuccess = () => {}, onFailed = () => {}, header = {}) {
  // console.log("请求方式：", "POST")
  request(loadingStr, url, params, "POST", onSuccess, onFailed, header);
}

/**
 * 供外部get请求调用
 */
function get(loadingStr, url, params, onSuccess = () => {}, onFailed = () => {}, header = {}) {
  // console.log("请求方式：", "GET")
  request(loadingStr, url, params, "GET", onSuccess, onFailed, header);
}

/**
 * function: 封装网络请求
 * @url URL地址
 * @params 请求参数
 * @method 请求方式：GET/POST
 * @onSuccess 成功回调
 * @onFailed  失败回调
 */

function request(loadingStr, url, params, method, onSuccess = () => {}, onFailed = () => {}, header = {}) {
  if (loadingStr != null) {
    wx.showLoading({
      title: typeof loadingStr == 'string' && loadingStr.length > 0 ? loadingStr : 'loading...',
      mask: true
    })
  }
  let defaultHeader = {
    'token': 'YVRGg6I0G28bYiTFYqOhQR928pOWcl1B',
    'content-type': 'application/json;charset=UTF-8'
  }
  header = {
    ...defaultHeader,
    ...header
  }
  console.log("🚀 ~ request ~ header:", header)
  // 除登录接口外要添加token
  // if(url.indexOf('/user/wxLogin') === -1) {
  //   const {globalData} = getApp();
  //   header.token = globalData.token;
  // }
  wx.request({
    url: url,
    data: dealParams(params),
    method: method,
    header: header,
    success: (res) => {
      if (loadingStr != null) {
        wx.hideLoading();
      }
      if (res.data) {
        /** start 根据需求 接口的返回状态码进行处理 
         *  只有1回调success 直接返回的接口数据结果
         */
        if (res.data.code == 200) {
          console.log('请求url：' + url, " \n参数：", params, '\n方式：', method, '\n响应：', res.data, "\n--- 这个没报错👆 ---");
          typeof onSuccess == 'function' && onSuccess(res.data); //request success
        } else {
          console.error('请求url：' + url, " \n参数：", params, '\n方式：', method, '\n响应：', res.data, "\n--- 注意code或者status👆 ---");
          if (debug) {
            //开发和测试环境 不判断code了 以后也没用了 每次进来都要取token
            typeof onFailed == 'function' && onFailed(res.data); //request failed
            return
          }
          switch (res.data.code) {
            case 10000: //如果一个页面俩接口可能跳两次 这里不清除本地数据 反正接口会报错 重构token有错就是10000!
              return
              // break
            case 10001:
              return
            default:
              typeof onFailed == 'function' && onFailed(res.data); //request failed
          }
        }
        /** end 处理结束*/
      }
    },
    fail: function (error) {
      // onFailed(""); //failure for other reasons

      console.error('请求url：' + url, " 参数：", params, '方式：', method, ' 失败：', error, "\n--- 你看到这个报错了吗？👆 ---");
      if (loadingStr != null) {
        wx.hideLoading();
      }
      let msg = 'error';
      console.log('-----')
      console.log(error)
      wx.showToast({
        title: 'error',
        icon: 'none',
        duration: 1500,
        mask: true
      });
    }
  })
}

function callAsyncFunction(requestUrl, method, params) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: requestUrl,
      data: dealParams(params),
      method: method,
      header: header,
      success: resolve,
      fail: reject
    })
  })
}


/**
 * function: 根据需求处理请求参数：添加固定参数配置等
 * @params 请求参数
 */
function dealParams(params) {
  // console.log("请求参数:", params)
  if (typeof params == "object") {
    params.version = version
    return params;
  } else {
    return {
      'version': version
    }
  }

}


// 1.通过module.exports方式提供给外部调用
module.exports = {
  postRequest: post,
  getRequest: get,
  callAsyncFunction: callAsyncFunction,
}